<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Install\Logic;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\Install\Command\UpgradeCommand;
use MoChat\App\Tenant\Contract\TenantContract;
use MoChat\App\User\Contract\UserContract;
use MoChat\Plugin\AdminUser\Contract\AdminUserContract;
use MoChat\Plugin\TenantProduct\Contract\TenantProductSkuContract;
use Psr\Container\ContainerInterface;
use Qbhy\HyperfAuth\AuthManager;

/**
 * 版本升级逻辑 1.3.0.
 */
class Upgrade1D3D0Logic
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject
     * @var AuthManager
     */
    protected $authManager;

    /**
     * @var AdminUserContract
     */
    protected $adminUserService;

    /**
     * @Inject
     * @var TenantProductSkuContract
     */
    protected $tenantProductSkuService;

    /**
     * @Inject
     * @var UserContract
     */
    protected $userService;

    /**
     * @Inject
     * @var TenantContract
     */
    protected $tenantService;

    /**
     * @var UpgradeCommand
     */
    private $command;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function __invoke(UpgradeCommand $command)
    {
        $this->command = $command;
        $this->createAdminUser();
        $this->resetTenantDefault();
    }

    /**
     * 创建超级管理员.
     */
    protected function createAdminUser(): bool
    {
        $this->command->line('创建超管后台管理员', 'info');
        // 手机号
        $phone = $this->command->askWithValidator('请输入管理员的手机号', function ($value) {
            if (is_numeric($value) && strlen($value) === 11) {
                return $value;
            }
            throw new \Exception('手机号错误');
        });

        $this->adminUserService = $this->container->get(AdminUserContract::class);
        $user = $this->adminUserService->getAdminUserByPhone($phone, ['id']);
        if (! empty($user)) {
            $this->command->warn('已经存在该管理员');
            return true;
        }

        // 密码
        $password = $this->command->secret('输入管理员密码', false);
        $encrypted = $this->authManager->guard('admin')->getJwtManager()->getEncrypter()->signature($password);
        return Db::table('admin_user')->insert([
            'phone' => $phone,
            'password' => $encrypted,
            'status' => 1,
            'parent_id' => 0,
            'is_root' => 1,
            'wallet_balance' => 9999999.00,
        ]);
    }

    /**
     * 重置租户默认值
     */
    protected function resetTenantDefault()
    {
        // 权限菜单
        $sku = $this->tenantProductSkuService->getTenantProductSkuById(1, ['attributes']);
        $attributes = $this->tenantProductSkuService->getTenantProductSkuValuesById(explode(',', $sku['attributes']));

        if (empty($attributes)) {
            return;
        }

        $roleMenu = '';
        foreach ($attributes as $v) {
            if ($v['attributeName'] === '套餐功能') {
                $roleMenu = $v['attributeValue'];
                break;
            }
        }

        $tenants = $this->tenantService->getTenantList([], ['id'], ['perPage' => 1000]);

        if (empty($tenants['data'])) {
            $this->command->info('无租户需要重置');
            return;
        }

        foreach ($tenants['data'] as $tenant) {
            $user = $this->userService->getRootUserByTenantId((int) $tenant['id'], ['id']);
            $this->tenantService->updateTenantById((int) $tenant['id'], [
                'max_employee' => 999999, // 不限制
                'max_corp' => 999999, // 不限制
                'expired_at' => date('Y-m-d', time() + 86400 * 365),
                'sku_id' => 1,
                'owner_id' => 1,
                'root_id' => ! empty($user) ? $user['id'] : 0,
                'role_menu' => $roleMenu,
            ]);
        }
    }
}
